package damagecalculator;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class XMLParser extends DefaultHandler {

    public static String[][] getInfo(String args) {
        info = new ArrayList();
        File file = new File("src/damagecalculator/items.xml");
        title = args.replace(" ", "_").toLowerCase();
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            DefaultHandler handler = new XMLParser();
            parser.parse(file, handler);
        } catch (Exception e) {
        }

        return items;
    }
    private static String tagname, name, tier, description, price, title;
    private StringBuffer lineBuffer;
    private static ArrayList info;
    private static String[][] items = null;
    private static boolean insideTag = false;

    @Override
    public void startElement(String ns, String ln, String qname, Attributes atts)
            throws SAXException {
        tagname = qname;
        lineBuffer = new StringBuffer();
        if (!insideTag && qname.equals(title)) {
            insideTag = true;
        }
    }

    @Override
    public void characters(char[] ch, int offset, int length)
            throws SAXException {
        lineBuffer.append(new String(ch, offset, length));
        if (insideTag) {
            if (tagname.equals("name")) {
                name = lineBuffer.toString().trim();
            } else if (tagname.equals("tier")) {
                tier = lineBuffer.toString().trim();
            } else if (tagname.equals("price")) {
                price = lineBuffer.toString().trim();
            } else if (tagname.equals("description")) {
                description = lineBuffer.toString().trim();
            }
        }
    }

    @Override
    public void endElement(String ns, String ln, String qname)
            throws SAXException {
        if (insideTag && qname.equals("description")) {
            info.add(new String[]{name, tier, price, description});
        }
        if (insideTag && qname.equals(title)) {
            insideTag = false;
            items = new String[info.size()][4];
            info.toArray(items);
        }
    }
}